package com.xinke.edu.mypetadoption.Activity.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.AppCompatButton;
import com.bumptech.glide.Glide;
import com.xinke.edu.mypetadoption.R;
import com.xinke.edu.mypetadoption.util.ShoppingCartManager;

import java.util.ArrayList;
import java.util.List;

public class ShoppingCartAdapter extends RecyclerView.Adapter<ShoppingCartAdapter.ShoppingCartViewHolder> {
    private List<CartItem> cartItems = new ArrayList<>();
    private OnCartItemChangeListener onCartItemChangeListener;

    public ShoppingCartAdapter() {
    }

    // 设置购物车数据
    public void setCartItems(List<CartItem> cartItems) {
        this.cartItems = cartItems != null ? cartItems : new ArrayList<>();
        notifyDataSetChanged();
        if (onCartItemChangeListener != null) {
            onCartItemChangeListener.onCartChanged();
        }
    }

    // 添加购物车项
    public void addCartItem(CartItem item) {
        cartItems.add(item);
        notifyItemInserted(cartItems.size() - 1);
        if (onCartItemChangeListener != null) {
            onCartItemChangeListener.onCartChanged();
        }
    }

    // 获取所有购物车项
    public List<CartItem> getCartItems() {
        return cartItems;
    }

    // 计算总价
    public double calculateTotalPrice() {
        double totalPrice = 0.0;
        for (CartItem item : cartItems) {
            totalPrice += item.getPrice() * item.getQuantity();
        }
        return totalPrice;
    }

    @Override
    public ShoppingCartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_shopping_cart, parent, false);
        return new ShoppingCartViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ShoppingCartViewHolder holder, int position) {
        if (cartItems != null && position < cartItems.size()) {
            CartItem item = cartItems.get(position);
            
            // 绑定数据
            holder.productName.setText(item.getName());
            holder.productPrice.setText("¥" + String.format("%.2f", item.getPrice()));
            holder.quantity.setText(String.valueOf(item.getQuantity()));
            
            // 暂时使用默认图片，实际应该从网络加载
            // 如果有图片加载库，可以在这里加载图片
            
            // 减号按钮点击事件
            holder.btnMinus.setOnClickListener(v -> {
                int currentQuantity = item.getQuantity();
                if (currentQuantity > 1) {
                    item.setQuantity(currentQuantity - 1);
                    holder.quantity.setText(String.valueOf(item.getQuantity()));
                    // 更新全局购物车数据
                    ShoppingCartManager.getInstance().updateItemQuantity(item.getProductId(), currentQuantity - 1);
                    if (onCartItemChangeListener != null) {
                        onCartItemChangeListener.onCartChanged();
                    }
                } else {
                    // 数量为1时，再点击减号自动删除商品
                    if (position != RecyclerView.NO_POSITION) {
                        // 从全局购物车管理器中移除商品
                        ShoppingCartManager.getInstance().removeItem(item.getProductId());
                        cartItems.remove(position);
                        notifyItemRemoved(position);
                        notifyItemRangeChanged(position, cartItems.size());
                        if (onCartItemChangeListener != null) {
                            onCartItemChangeListener.onCartChanged();
                        }
                        Toast.makeText(v.getContext(), "商品已删除", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            
            // 加号按钮点击事件
            holder.btnPlus.setOnClickListener(v -> {
                int currentQuantity = item.getQuantity();
                item.setQuantity(currentQuantity + 1);
                holder.quantity.setText(String.valueOf(item.getQuantity()));
                // 更新全局购物车数据
                ShoppingCartManager.getInstance().updateItemQuantity(item.getProductId(), currentQuantity + 1);
                if (onCartItemChangeListener != null) {
                    onCartItemChangeListener.onCartChanged();
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return cartItems.size();
    }

    // 购物车项数据类
    public static class CartItem {
        private String name;
        private double price;
        private int quantity;
        private String imageUrl;
        private int productId;

        public CartItem(String name, double price, int quantity, String imageUrl, int productId) {
            this.name = name;
            this.price = price;
            this.quantity = quantity;
            this.imageUrl = imageUrl;
            this.productId = productId;
        }

        // Getters and Setters
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public double getPrice() { return price; }
        public void setPrice(double price) { this.price = price; }
        public int getQuantity() { return quantity; }
        public void setQuantity(int quantity) { this.quantity = quantity; }
        public String getImageUrl() { return imageUrl; }
        public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; }
        public int getProductId() { return productId; }
        public void setProductId(int productId) { this.productId = productId; }
    }

    // 购物车变更监听器
    public interface OnCartItemChangeListener {
        void onCartChanged();
    }

    public void setOnCartItemChangeListener(OnCartItemChangeListener listener) {
        this.onCartItemChangeListener = listener;
    }

    static class ShoppingCartViewHolder extends RecyclerView.ViewHolder {
        ImageView productImage;
        TextView productName;
        TextView productPrice;
        TextView quantity;
        AppCompatButton btnMinus;
        AppCompatButton btnPlus;

        public ShoppingCartViewHolder(View itemView) {
            super(itemView);
            productImage = itemView.findViewById(R.id.shoppingCart_image);
            productName = itemView.findViewById(R.id.shoppingCart_name);
            productPrice = itemView.findViewById(R.id.shoppingCart_price);
            quantity = itemView.findViewById(R.id.tv_count1);
            btnMinus = itemView.findViewById(R.id.btn_minus1);
            btnPlus = itemView.findViewById(R.id.btn_plus1);
        }
    }
}